## Summary statistics of control variables ##

p_load(Hmisc)

svysummary_ctrl <- data.frame(matrix(ncol = 8, nrow = 0))

for (i in ctrlvars) {
  for (j in c(0,1)) {
    for (k in c(0,1)){
      p <- pool %>% filter(scst == j, wave == k, !is.na(pool[i]))
      m = wtd.mean(p[i],p$weights)
      sd = sqrt(wtd.var(p[i],p$weights))
      min = min(p[i])
      max = max(p[i])
      df <- data.frame(attribute =  i,
                       scst =  j,
                       wave =  k,
                       n = nrow(na.omit(p[i])),
                       mean = signif(m,3),
                       sd = signif(sd,3),
                       min = min,
                       max = max)
      svysummary_ctrl <- rbind(svysummary_ctrl, df)
      rm(p,m,sd,min,max,df)
    }
  }
}


svysummary_ctrl <- svysummary_ctrl %>% 
  mutate(attribute = fct_recode(as.factor(attribute),
                                "Respondent Age" = "age",
                                "Respondent Gender (Male == 1)" = "gender_male",
                                "Religion (Hindu == 1)" = "religion_hindu",
                                "Religion (Muslim == 1)" = "religion_muslim",
                                "Religion (Others == 1)" = "religion_others",
                                "Education (< 10th Standard)" = "education_below10th", 
                                "Education (>= 10th Standard)" = "education_atleast10th",
                                "Household Size" = "hhsize",
                                "Monthly Expenditure" = "month_exp",
                                "BPL/Antyodaya Ration Card (==1)" = "bplaay"),
         scst = fct_recode(as.factor(scst),
                           "SC/ST" = "1",
                           "All Others" = "0")) %>% 
  arrange(attribute)

svysummary_ctrl_wave1 <- svysummary_ctrl %>% filter(wave == 0) %>% select(-wave)
svysummary_ctrl_wave2 <- svysummary_ctrl %>% filter(wave == 1) %>% select(-wave)

colnames(svysummary_ctrl_wave1) <- c("Attribute", "Caste", "Obs. Wave 1", "Mean Wave 1", "SD Wave 1", "Min Wave 1", "Max Wave 1")
colnames(svysummary_ctrl_wave2) <- c("Attribute", "Caste", "Obs. Wave 2", "Mean Wave 2", "SD Wave 2", "Min Wave 2", "Max Wave 2")

detach(name = package:Hmisc, force = T)
